import { Module } from 'vuex'
import type { TRootState } from '../type'
import type { TDwnState } from './type'

import { getDownMusic, putLikeMusic } from '@/service/my-music'
import localCache from '@/utils/cache'
import { Message } from '@/utils/message'
import { formatObjName } from '@/utils/format-arr'

const DownModule: Module<TDwnState, TRootState> = {
  namespaced: true,
  state() {
    return {
      downMusic: []
    }
  },
  getters: {},
  mutations: {
    updateDwn(state, pyload) {
      state.downMusic = pyload
    },
    pushDwn(state, pyload) {
      state.downMusic.push(pyload)
      localCache.setCache('downMusics', state.downMusic)
    }
  },
  actions: {
    loadLocalDown({ commit, state }) {
      const dwnMusic = localCache.getCache('downMusics')
      if (!dwnMusic) {
        localCache.setCache('downMusics', state.downMusic)
      }
      commit('updateDwn', localCache.getCache('downMusics'))
    },
    async downMusic({ commit }, pyload) {
      const result: any = await getDownMusic(pyload.id)
      const url = result.data.url
      if (url) {
        window.open(url, '_blank')
        pyload = formatObjName(pyload, {
          duration: 'dt',
          artists: 'ar',
          album: 'al'
        })
        commit('pushDwn', pyload)
      } else {
        Message('该歌曲为付费歌曲，不能下载~', 'warning')
      }
    },
    async pullLike({ commit }, pyload) {
      const { id, like } = pyload
      const result = await putLikeMusic(id, like)
      if (result.code == 200) {
        const str = like ? '收藏成功' : '取消收藏成功'
        Message(str, 'success')
        return
      }
      Message('收藏失败,请登录', 'error')
    }
  }
}
export default DownModule

// 测试数据
// {
//   ar: [
//     {
//       albumSize: 0,
//       alias: [],
//       id: 12250109,
//       img1v1: 0,
//       img1v1Url:
//         'https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg',
//       name: 'Bruno Major',
//       picId: 0,
//       picUrl: null,
//       trans: null
//     }
//   ],
//   al: {
//     copyrightId: 631010,
//     id: 35093179,
//     mark: 0,
//     name: 'Easily',
//     picId: 109951163253947140,
//     publishTime: 1480032000000,
//     size: 1,
//     status: 0
//   },
//   copyrightId: 631010,
//   dt: 210240,
//   fee: 8,
//   ftype: 0,
//   id: 449577802,
//   mark: 262144,
//   mvid: 5854025,
//   name: 'Easily',
//   rUrl: null,
//   rtype: 0,
//   status: 0
// }
